package main.api;

import main.RequestHelper;
import main.ResponseHelper;
import main.database.CollectionHelper;
import org.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class CollectionApi {
    @PostMapping("/api/collect")
    public ResponseEntity<?> collect(HttpServletRequest request) {
        Map<String, String[]> map = request.getParameterMap();

        String fictionId = null;

        String uuid = RequestHelper.getUserUUIDFromRequest(request);

        if (map.containsKey("id")) {
            fictionId = map.get("id")[0];
        }

        if (uuid == null || fictionId == null || uuid.isEmpty() || fictionId.isEmpty()) {
            return ResponseEntity.ok(ResponseHelper.createBasicJsonObject(404, "参数有错误：token或者fiction id无效").toString());
        }

        boolean result = CollectionHelper.toggleUserCollect(uuid, fictionId);
        JSONObject response = ResponseHelper.createBasicJsonObject(200, "ok");
        response.put("collect", result);
        return ResponseEntity.ok(response.toString());
    }

    @PostMapping("/api/uncollectall")
    public ResponseEntity<?> uncollectall(HttpServletRequest request) {
        Map<String, String[]> map = request.getParameterMap();
        String[] fictionIdArray = null;

        String result;
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        if (uuid == null || uuid.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "没有登录").toString();
        }
        else {
            if (map.containsKey("idarray[]")) {
                fictionIdArray = map.get("idarray[]");
            }

            if (fictionIdArray == null) {
                result = ResponseHelper.createBasicJsonObject(404, "没有idarray参数").toString();
            }
            else if (fictionIdArray.length == 0) {
                result = ResponseHelper.createBasicJsonObject(404, "没有任何需要取消的东西，忽略").toString();
            }
            else {
                for (int i = 0; i < fictionIdArray.length; ++i) {
                    CollectionHelper.toggleUserCollect(uuid, fictionIdArray[i]);
                }

                result = ResponseHelper.createBasicJsonObject(200, "ok").toString();
            }
        }

        return ResponseEntity.ok(result);
    }
}
